<?php

namespace App\Http\Controllers\Admin;

use App\Exports\StoreExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Store;
use App\Models\Categorys;
use App\Models\Stores;
use App\Models\Mails;
use App\Models\Users;
use App\Models\Wechat;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class StoreController extends Controller {

    /**
     * 页面
     * @return view
     */
    public function index(Request $request){
        $params = [
            'page' => 1,
            'kwd' => '',
            'index_recomment' => 0,
            'recommend' => 0,
            'status' => 0,
            'cid' => 0,
            'start' => '',
            'end' => '',
        ];
        //如果从代办点击过来，则显示待审核
        $from = $request->get('from',0);
        if ($from == 1){
            $params['status'] = 2;
            $from = 0;
        }
        $params = json_encode($params);
        //获取分类
        $categorys = Categorys::getCascaderList();
        $categorys = json_encode($categorys);
        return view('admin.store.index',compact('categorys','params'));
    }

    /**
     * 列表数据
     * @param Request $request
     * @return bool
     */
    public function list(Request $request){
        try{
            $params = [
                'kwd' => (string)$request->get('kwd',''),
                'index_recomment' => (int)$request->get('index_recomment',0),
                'recommend' => (int)$request->get('recommend',0),
                'status' => (int)$request->get('status',0),
                'cid' => (int)$request->get('cid',0),
                'start' => (string)$request->get('start',''),
                'end' => (string)$request->get('end',''),
            ];
            $lists = Stores::getList($params);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 编辑
     * @param Request $request
     * @return bool|view
     */
    public function edit(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $info = [];
            $cate = [];
            if($id){
                $info = Stores::findOrFail($id);
                $cate = Categorys::where('pid',0)->where('status','<>',-1)->orderBy('sort','asc')->get(['id','name','pid']);
                $info['reason'] = '';//19-9-20 by z
                //将一级分类和二级分类拼接
                if(!empty($info['cate_id']) && !empty($info['cate_pid'])){
                    $info['ids'] = $info['cate_id'].",".$info['cate_pid'];
                }else{
                    if(!empty($info['cate_id'])){
                        $info['ids'] = $info['cate_id'];
                    }elseif (!empty($info['cate_pid'])){
                        $info['ids'] = $info['cate_pid'];
                    }
                }
                $info['ids'] = !empty($info['ids']) ? explode(',',$info['ids']) : 0;

                foreach ($info['ids'] as $k => $v){
                    $pid=Categorys::getPid($v);
                    if($pid > 0){
                        $pidTree[$k][]="$pid";
                        $pidTree[$k][]=$v;
                    }else{
                        $pidTree[$k][]=$v;
                    }
                }
                $info['cate_id'] = $pidTree;
            }
            $info = json_encode($info);
            $cate = json_encode($cate);
            //获取分类
            $categorys = Categorys::getCascaderList();
            $categorys = json_encode($categorys);
            return view('admin.store.store_update',compact('info','id','date','categorys','cate'));
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 统计详情
     * @param Request $request
     * @return bool|view
     */
    public function detail(Request $request){
        try{
            return view('admin.store.store_detail');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 更新
     * @param Store $request
     * @param array_push 将字符串push成数组
     * @param array_unique 数组去重
     * @return bool
     */
    public function update(Request $request)
    {
        try{
            $data = $request->all();
            $str1 = [];
            $str2 = [];
            foreach ($data['cate_id'] as $k=>$v) {
                array_push($str1, $v[0]);
                if (isset($v[1])){
                    array_push($str2, $v[1]);
                }
            }
            $data['cate_pid'] = implode(",",array_unique($str1));
            $data['cate_id'] = implode(",",array_unique($str2));
            if($data['id']){
                $info = Stores::findOrFail($data['id']);
                //19-9-20 by z 除正常状态意外其余需给用户发送站内信告知原因 start
                if($data['status'] != 1){
                    $reason = $data['reason'];
                    if(empty($reason)){
                        return $this->writeJson(1, null, '请填写相关状态原因！');
                    }
                    if($data['status'] == 2 || $data['status'] == 3){
                        $title = '店铺审核通知';
                    }elseif ($data['status'] == 4){
                        $title = '店铺关闭通知';
                    }
                    Mails::sendMails($title,$data['reason'],$info['user_id'],1);
                }
                //end
                $info->update($data);
                return $this->writeJson(0,null,'修改信息成功');
            }else{
                unset($data['id']);
                Stores::create($data);
                return $this->writeJson(0,null,'新增信息成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 拒绝
     * @param Request $request
     * @return bool
     */
    public function lock(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $reason = (string)$request->get('reason', '');
            if(empty($id) || empty($reason)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Stores::findOrFail($id);
            $info->update(['status' => Stores::STATUS_3]);

            //19-9-23 by z 未通过发送站内信 start
            Mails::sendMails('店铺审核未通过通知',$reason,$info['user_id'],1);
            //end

            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 通过
     * @param Request $request
     * @return bool
     */
    public function active(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Stores::findOrFail($id);
            $info->update(['status' => Stores::STATUS_1]);
            //审核通过、推送微信消息
            $user_info = Users::where(['id'=>$info['user_id']])->where('status','<>',-1)->first(['id','mobile','username','openid']);
            if (!empty($user_info['openid'])){
                $template_id = '9dp0uDLyRbtzu2q9NjDvs6M12rPBhZ_p3-k7xzNfHaQ';
                $url = 'http://wap.hrqidian.com/#/supDetail?store_id='.$id;
                $data = [
                    'first' => '亲爱的供应商，您的店铺已完成审核',
                    'keyword1' => $user_info['username'],
                    'keyword2' => $user_info['mobile'],
                    'keyword3' => '审核通过',
                    'keyword4' => '请登陆个人中心查看',
                    'remark' => 'HR小启客服',
                ];
                Wechat::wechatSend($user_info['openid'], $template_id, $url, $data);
            }
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 关店
     * @param Request $request
     * @return bool
     */
    public function close(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $reason = (string)$request->get('reason', '');
            if(empty($id) || empty($reason)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Stores::findOrFail($id);
            $info->update(['status' => Stores::STATUS_4]);

            //19-9-23 by z 下架发送站内信 start
            Mails::sendMails('店铺下架通知',$reason,$info['user_id'],1);
            //end

            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 单个/多个删除
     * @param Request $request
     * @return bool
     */
    public function destroy(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            if(!is_array($id)){
                $id=[$id];
            }
            //修改软删除 19-7-31
            $data['status'] = -1;
            Stores::whereIn('id',$id)->update($data);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     *  Excel导出
     * @param Request $request
     * @return bool
     */
    public function exports(Request $request)
    {
        $ids = $request->get('ids');
        $export = new StoreExport($ids);
        //这里可以传参到服务层
        return Excel::download($export, '店铺表'.date("Y-m-d H:i:s").'.xlsx');
    }

}
